<?php
class Server {
    private $serv;

    public function __construct() {
        $this->serv = new swoole_server( "0.0.0.0", 9501 );
        $this->serv->set( array(
            'worker_num'    => 8,
            'task_worker_num'   => 8,
            'daemonzize'     => false,
            'max_request'    => 10000,
            'dispatch_mode'  => 2,
            'debig_mode'     => 1
        ) );
        
        $this->serv->on('WorkerStart', array($this, 'onWorkerStart'));
        $this->serv->on( 'Start', array($this, 'onStart') );
        $this->serv->on( 'Connect', array($this, 'onConnect') );
        $this->serv->on( 'Receive', array($this, 'onRecevice') );
        $this->serv->on( 'Close', array($this, 'onClose') );
        $this->serv->on( 'Task', array($this, 'onTask'));
        $this->serv->on( 'Finish', array($this, 'onFinish'));
        // $this->serv->on('Timer', array($this, 'onTimer'));

        $this->serv->start();
    }

    public function onStart( $serv ) {
        echo "Start\n";
    }

    public function OnWorkerStart($serv, $worker_id) {
        // codes....
    }

    public function onConnect( $serv, $fd, $from_id ) {
        $serv->send( $fd, "Hello {$fd}" );
    }

    public function onRecevice( swoole_server $serv, $fd, $from_id, $data ) {
        echo "Get message from client {$fd}:{$from_id} and {$data}\n";
        $param = array(
            'fd'    => $fd,
        );

        // start a task
        $serv->task( json_encode($param) );
        echo "Continue handle worker\n";
    }
    
    public function onTask($serv, $task_id, $from_id, $data) {
        echo "This Task{$task_id} from worker {$from_id}\n";
        echo "Data: {$data}";
        for ( $i = 0; $i < 10; $i++ ) {
            sleep(1);
            echo "Task {$task_id} handle {$i} times.....\n";
        }
        $fd = json_decode( $data, true)['fd'];
        $serv->send( $fd, "Data in Task {$task_id}\n");
        return "task {$task_id} resul";
    }
    
    public function onFinish($serv, $task_id, $data) {
        echo "Task {$task_id} finished@\n";
        echo "Result: {$data}\n";
    }

    public function onClose( $serv, $fd, $from_id) {
        echo "Client {$fd} close connection\n";
    }

}

$server = new Server();
